package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bean.User;
import com.example.domain.SysUser;
import com.example.domain.vo.SysUserVo;
import com.example.mapper.SysUserMapper;
import com.example.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    private List<SimpleGrantedAuthority> authorities;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名从数据库中查询用户信息，如果不存在则抛出异常
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,username);
        SysUser user = sysUserMapper.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //从数据库中存储的角色列表
//        List<String> roleList = sysUserMapper.selectRoleByUserId(user.getUserId());

        List<String> permList = sysUserMapper.selectPermsByUserId(user.getUserId());


        SysUserVo sysUserVo = new SysUserVo();
        BeanUtil.copyProperties(user,sysUserVo);
//        sysUserVo.setRoles(roleList);
        sysUserVo.setPermList(permList);

        // 返回一个UserDetails对象，包含用户名、密码、角色等信息
        return new org.springframework.security.core.userdetails.User(
                user.getUserName(),
                user.getPassword(),
                getAuthorities(sysUserVo.getPermList()));
    }

    // 将用户的角色转换为GrantedAuthority对象的集合，用于授权判断
    private Collection<? extends GrantedAuthority> getAuthorities(List<String> perms) {
        return perms.stream().map(perm -> new SimpleGrantedAuthority( perm)).collect(Collectors.toList());
    }
}
